<?php

namespace app\controller\crm;

use app\BaseController;
use app\common\DataPermissionHelper;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;

/**
 * 销售机会线索管理
 */
class Opportunity extends BaseController
{
    /**
     * 获取机会线索列表
     */
    public function list()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $customerId = $params['customer_id'] ?? 0;
        $category = $params['category'] ?? '';
        $level = $params['level'] ?? '';
        $status = $params['status'] ?? '';

        $query = Db::name('crm_opportunity')
            ->alias('o')
            ->field('o.*, c.name as customer_name, c.customer_type, ct.name as contact_name, u.name as user_name')
            ->leftJoin('crm_customer c', 'o.customer_id = c.id')
            ->leftJoin('crm_contact ct', 'o.contact_id = ct.id')
            ->leftJoin('admin u', 'o.user_id = u.id')
            ->where('o.delete_time', 0);

        if ($customerId) {
            $query->where('o.customer_id', $customerId);
        }

        if ($category) {
            $query->where('o.category', $category);
        }

        if ($level) {
            $query->where('o.level', $level);
        }

        if ($status) {
            $query->where('o.status', $status);
        }

        // 数据权限控制
        $userId = $this->getUserId();
        if ($userId > 0) {
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();

            if ($userInfo) {
                // 超级管理员和部门经理可以查看所有数据
                if ($userInfo['group_id'] == 1 || $userInfo['group_id'] == 2) {
                    // 部门经理只能查看本部门数据
                    if ($userInfo['group_id'] == 2) {
                        $query->where('o.department_id', $userInfo['did']);
                    }
                } else {
                    // 销售人员只能查看自己的数据
                    $query->where('o.user_id', $userId);
                }
            }
        }

        $total = $query->count();
        $list = $query->order('o.create_time', 'desc')
            ->page($page, $limit)
            ->select();

        return $this->paginate($list ? $list->toArray() : [], $total, (int)$page, (int)$limit);
    }

    /**
     * 获取机会线索详情
     */
    public function detail()
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        $opportunity = Db::name('crm_opportunity')
            ->alias('o')
            ->field('o.*, c.name as customer_name, c.customer_type, ct.name as contact_name, ct.phone as contact_phone')
            ->leftJoin('crm_customer c', 'o.customer_id = c.id')
            ->leftJoin('crm_contact ct', 'o.contact_id = ct.id')
            ->leftJoin('admin u', 'o.user_id = u.id')
            ->where('o.id', $id)
            ->where('o.delete_time', 0)
            ->find();

        if (!$opportunity) {
            return $this->error('机会线索不存在');
        }

        // 检查数据权限
        if (!$this->checkDataPermission($opportunity)) {
            return $this->error('没有权限访问此数据', 403);
        }

        // 获取关联的跟进记录
        $followups = Db::name('crm_followup')
            ->where('opportunity_id', $id)
            ->where('delete_time', 0)
            ->order('create_time', 'desc')
            ->select();

        $opportunity['followups'] = $followups ? $followups->toArray() : [];

        return $this->success($opportunity);
    }

    /**
     * 新增机会线索
     */
    public function add()
    {
        try {
            // 开始事务
            Db::startTrans();
            
            $params = Request::param();
            $userId = $this->getUserId();
            
            // 记录请求参数日志
            Log::info('CRM Opportunity add request params:', $params);

            if (!$userId) {
                Log::warning('CRM Opportunity add failed: user not logged in');
                Db::rollback();
                return $this->error('未登录或登录已过期', 401);
            }

            // 获取用户部门信息
            $userInfo = Db::name('admin')
                ->field('did')
                ->where('id', $userId)
                ->find();

            // 确保包含所有必填字段
            $data = [
                'customer_id' => $params['customer_id'],
                'contact_id' => isset($params['contact_id']) ? (int)$params['contact_id'] : 0,  // 允许为0（无联系人）
                'discovery_date' => !empty($params['discovery_date']) ? (is_numeric($params['discovery_date']) ? $params['discovery_date'] : strtotime($params['discovery_date'])) : time(),
                'category' => $params['category'],
                'level' => $params['level'],
                'description' => $params['description'] ?? '',
                'title' => $params['title'] ?? '',
                'expected_sign_date' => !empty($params['expected_sign_date']) ? (is_numeric($params['expected_sign_date']) ? $params['expected_sign_date'] : strtotime($params['expected_sign_date'])) : 0,
                'expected_amount' => $params['expected_amount'] ?? 0,
                'remarks' => $params['remarks'] ?? '',
                'status' => 1,  // 默认有效
                'user_id' => $userId,
                'department_id' => $userInfo['did'] ?? 0,
                'create_time' => time(),
                'update_time' => time()
            ];

            // 验证必填字段是否存在（contact_id允许为0）
            $requiredFields = ['user_id', 'department_id', 'create_time', 'customer_id', 'category', 'level', 'title', 'description', 'expected_sign_date', 'expected_amount'];
            foreach ($requiredFields as $field) {
                if (!isset($data[$field]) || (empty($data[$field]) && $data[$field] !== 0 && $data[$field] !== '0')) {
                    Log::warning('CRM Opportunity missing required field: ' . $field);
                    Db::rollback();
                    return $this->error('缺少必要字段：' . $field);
                }
            }

            // 记录准备插入的数据
            Log::info('CRM Opportunity add data to insert:', $data);
            
            $id = Db::name('crm_opportunity')->insertGetId($data);
            
            // 记录插入结果
            if ($id) {
                // 提交事务
                Db::commit();
                Log::info('CRM Opportunity add success:', ['id' => $id]);
                return $this->success(['id' => $id], '添加成功');
            } else {
                // 回滚事务
                Db::rollback();
                Log::error('CRM Opportunity add failed: insertGetId returned false');
                return $this->error('添加失败');
            }
        } catch (\Exception $e) {
            // 发生异常，回滚事务
            Db::rollback();
            
            // 记录异常信息
            Log::error('CRM Opportunity add exception:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 编辑机会线索
     */
    public function edit()
    {
        $params = Request::param();
        $id = $params['id'] ?? 0;

        if (!$id) {
            return $this->error('参数错误');
        }

        // 检查机会线索是否存在
        $opportunity = Db::name('crm_opportunity')->where('id', $id)->find();
        if (!$opportunity) {
            return $this->error('机会线索不存在');
        }

        // 检查数据权限
        if (!$this->checkDataPermission($opportunity)) {
            return $this->error('没有权限修改此数据', 403);
        }

        // 检查线索等级是否为A或B，如果是则不允许修改
        if (in_array($opportunity['level'], [1, 2]) && $opportunity['level'] != $params['level']) {
            return $this->error('线索等级一旦设定为A或B后不可变更');
        }

        $data = [
            'contact_id' => $params['contact_id'] ?? null,
            'discovery_date' => !empty($params['discovery_date']) ? (is_numeric($params['discovery_date']) ? $params['discovery_date'] : strtotime($params['discovery_date'])) : time(),
            'category' => $params['category'],
            'level' => $params['level'],
            'description' => $params['description'] ?? '',
            'title' => $params['title'] ?? '',
            'expected_sign_date' => !empty($params['expected_sign_date']) ? (is_numeric($params['expected_sign_date']) ? $params['expected_sign_date'] : strtotime($params['expected_sign_date'])) : 0,
            'expected_amount' => $params['expected_amount'] ?? 0,
            'remarks' => $params['remarks'] ?? '',
            'status' => $params['status'] ?? 1,
            'update_time' => time()
        ];

        $result = Db::name('crm_opportunity')->where('id', $id)->update($data);

        if ($result !== false) {
            return $this->success([], '修改成功');
        }

        return $this->error('修改失败');
    }

    /**
     * 转化为订单
     */
    public function convert()
    {
        $params = Request::param();
        $id = $params['id'] ?? 0;

        if (!$id) {
            return $this->error('参数错误');
        }

        // 检查机会线索是否存在且有效
        $opportunity = Db::name('crm_opportunity')->where('id', $id)->find();
        if (!$opportunity) {
            return $this->error('机会线索不存在');
        }

        if ($opportunity['status'] != 1) {
            return $this->error('机会线索已转化或已失效');
        }

        // 检查数据权限
        if (!$this->checkDataPermission($opportunity)) {
            return $this->error('没有权限操作此数据', 403);
        }

        // TODO: 这里需要根据线索类别创建相应的订单
        // 由于订单模块在第二阶段开发，这里先标记为已转化
        Db::name('crm_opportunity')->where('id', $id)->update([
            'status' => 2,  // 已转化
            'update_time' => time()
        ]);

        return $this->success([], '转化成功，请前往订单模块创建订单');
    }

    /**
     * 删除机会线索（软删除）
     */
    public function delete()
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        // 检查机会线索是否存在
        $opportunity = Db::name('crm_opportunity')->where('id', $id)->find();
        if (!$opportunity) {
            return $this->error('机会线索不存在');
        }

        // 检查数据权限
        if (!$this->checkDataPermission($opportunity)) {
            return $this->error('没有权限删除此数据', 403);
        }

        $result = Db::name('crm_opportunity')->where('id', $id)->update([
            'delete_time' => time()
        ]);

        if ($result !== false) {
            return $this->success([], '删除成功');
        }

        return $this->error('删除失败');
    }

    /**
     * 检查数据权限
     */
    private function checkDataPermission($opportunity)
    {
        $userId = $this->getUserId();
        if (!$userId) {
            return false;
        }

        $userInfo = Db::name('admin')
            ->field('id, group_id, did')
            ->where('id', $userId)
            ->find();

        if (!$userInfo) {
            return false;
        }

        // 超级管理员
        if ($userInfo['group_id'] == 1) {
            return true;
        }

        // 部门经理
        if ($userInfo['group_id'] == 2) {
            return $userInfo['did'] == $opportunity['department_id'];
        }

        // 销售人员只能操作自己的数据
        return $opportunity['user_id'] == $userId;
    }
}
